package com.koron.common.web.controller;

import com.koron.bean.base.Response;
import com.koron.common.core.business.configsettings.utils.ConfigInfoTool;
import com.koron.common.core.config.ThreadLocalContext;
import com.koron.common.core.util.RsaEncrypt;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@Api(tags = "帆软地址")
@Slf4j
@RestController
@RequestMapping("/finereport")
public class FineReportController {

    private static String defaultKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAhk7aWf1te2Ypm4hSKaKtU9V6KqRgqDT4\n" +
            "PBZAfpbj8zGZWXT93b+s6/CF31IypdnRvoAT0+HpysUJxKIpwKzmqs3rGDjh3Oap7tMgI5VOzPT3\n" +
            "k+jjrKRAdhFBFJltRRFCfn11jqpkGOIgBzLY/e8XUaiPZ9q6zzEmUBolLv96wybAunnerTsa81TJ\n" +
            "zkrh9/OD63LrMmcaWPrerfVp8Pb40VzpRpYyXwP1f3XX9kR6Y0zTNkM7HHEDlG8Q+aZi03JgqXAE\n" +
            "+Z0p3ADvz8AN1MSbiZ0i5Pwys+Fz0A9V7naf9xezaREHpOIpmC7cbCuKqiqr1uxYNBTOaoVR5c4r\n" +
            "q21dNQIDAQAB";

    private String getCurrDs() {
        return ThreadLocalContext.get().getCurrDs();
    }

    @ApiOperation(value = "获取地址")
    @GetMapping("/getAddress")
    public Response<String> getAddress() {
        Map<String, String> map = ConfigInfoTool.getConfigByCode("common", "fineReport");
        String address = map.get("address");
        return Response.ok(address);
    }


    /**
     * 公钥加密后可直接单点
     * http://119.236.204.154:8088/webroot/decision?ssoToken=
     *
     * @return
     * @throws UnsupportedEncodingException
     */
    @ApiOperation(value = "帆软单点")
    @GetMapping("/frCas")
    public Response<HashMap> frCas() throws UnsupportedEncodingException {
        // 帆软地址
        Map<String, String> map = ConfigInfoTool.getConfigByCode("common", "fineReport");
        HashMap returnmap = new HashMap();
        returnmap.put("address", map.get("address"));

        // 帆软单点公钥加密
        String text = System.getProperty("text");
        String key = System.getProperty("publicKey");
        String username = text == null ? "admin" : text;

        //从插件配置页面获取
        String publicKey = key == null ? defaultKey : key;

        //加密后的ssoToken,可以在前台界面进行解密测试
        String encrypt = RsaEncrypt.encrypt(username, publicKey);
        log.info("encrypted username: " + encrypt);

        //encode后的token,可以直接放于url上进行单点
        String encode = URLEncoder.encode(encrypt, "UTF-8");
        log.info("ssoToken: " + encode);
        returnmap.put("ssoToken", encode);

        return Response.ok(returnmap);
    }
}
